#!/usr/bin/env python
# -*- coding: utf-8 -*-

#import wx
#import os
import sys
#from core.ide.themesmanager import ThemesManager
#from core.ide.commandmanager import CommandManager
from extensions.tools.project.localobj import *
from core.ui.menu import *
#from core import Core
import core.utils.osutils as osutils
import subprocess
#from tooltips import ToolTips

try:
    from agw import customtreectrl as CT
except ImportError: # if it's not there locally, try the wxPython lib.
    import wx.lib.agw.customtreectrl as CT


#TODO TreeCtrl bug on window wxpython2.9.3 and wxpython2.9.4 when draging object on project
if sys.platform == "win32" and False:
    class TreeManagerFix(CT.CustomTreeCtrl):
        def __init__(self,parent):
            #wx.TreeCtrl.__init__(self, parent, -1, (0,2), (200, 300), wx.TR_HIDE_ROOT | wx.TR_DEFAULT_STYLE | wx.TR_EDIT_LABELS)
            CT.CustomTreeCtrl.__init__(self, parent, -1, (0,2), (200, 300), style=wx.BORDER_SIMPLE | wx.WANTS_CHARS | wx.HSCROLL, agwStyle=wx.TR_DEFAULT_STYLE | CT.TR_HAS_BUTTONS | CT.TR_HAS_VARIABLE_ROW_HEIGHT | wx.TR_HIDE_ROOT )
            self.SetBackgroundColour(wx.WHITE)
else:
    class TreeManagerFix(wx.TreeCtrl):
        def __init__(self,parent):
            wx.TreeCtrl.__init__(self, parent, -1, (0,2), (200, 300), wx.TR_HIDE_ROOT | wx.TR_DEFAULT_STYLE | wx.TR_EDIT_LABELS)

FILE_WINDOW = None
if sys.platform == "win32":
    FILE_WINDOW="explorer"
elif sys.platform.find("linux")==0:
    ed=osutils.detect_linux_desktop_environment()
    if ed=="gnome":
        FILE_WINDOW='nautilus'
    elif ed=="xfce":
        FILE_WINDOW='thunar'
    elif ed=="kde":
        FILE_WINDOW='dolphin'
elif sys.platform.find("mac")>-1:
    FILE_WINDOW='finder'



class TreeManager(TreeManagerFix):
#class TreeManager(CT.CustomTreeCtrl):
    def __init__(self,parent):
        TreeManagerFix.__init__(self,parent)
        #wx.TreeCtrl.__init__(self, parent, -1, (0,2), (200, 300), wx.TR_HIDE_ROOT | wx.TR_DEFAULT_STYLE | wx.TR_EDIT_LABELS)
        #CT.CustomTreeCtrl.__init__(self, parent, -1, (0,2), (200, 300), style=wx.BORDER_SIMPLE | wx.WANTS_CHARS, agwStyle=wx.TR_DEFAULT_STYLE | CT.TR_HAS_BUTTONS | CT.TR_HAS_VARIABLE_ROW_HEIGHT | wx.TR_HIDE_ROOT)
        self.root = self.AddRoot("The Root Item")
        #self.root=self.AppendItem(self.root1,"test")
        self._freeze=False
        self.SetBackgroundColour(wx.WHITE)
        #self.addSourcePath("ProjectTest", "../_project/python")
        self.mainItem=None
        self._selected=None
        self.Bind(wx.EVT_LEFT_DCLICK, self.onLeftDClick)
        self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self.onContextMenu)
        self.Bind(wx.EVT_TREE_ITEM_COLLAPSING,self.onCollapsing)
        self.Bind(wx.EVT_TREE_ITEM_EXPANDING,self.onExpand)
        self.Bind(wx.EVT_TREE_END_LABEL_EDIT,self.onRenameComplete)
        self.Bind(wx.EVT_TREE_BEGIN_DRAG,self.onStartDrag)
        self.Bind(wx.EVT_TREE_END_DRAG,self.onEndDrag)
        self.SetImageList(ThemesManager().getDefaultTheme().getWxLib("file_16"))
        self._tooltips=None
        CommandManager().listener("project/setMainDocument",self.setMainDocument)
        CommandManager().listener("project/addSource",self.addSource)
        CommandManager().listener("project/removeSource",self.removeSource)
        CommandManager().listener("project/rename",self.rename)
        CommandManager().listener("explore",self.exploreFile)
        CommandManager().listener("create_template",self.createTemplate)
     
       
    def createTemplate(self,dir_,template):
        child = self.AppendItem(dir_.item, os.path.basename(template))
        file_=File(dir_.path+"/"+os.path.basename(template))
        file_.data=template
        self.SetItemImage(child, file_.icon(), which = wx.TreeItemIcon_Normal)
        self.SetPyData(child, file_)
        self.rename(file_,child)
        #LangsManager().createTemple(path+"/"+os.path.basename(template), template)
    
    
    
    def addProject(self,project):
        self.project=project
        child = self.AppendItem(self.root, project.name)
        self.SetItemImage(child, ThemesManager().getDefaultTheme().getWxIdImage("file_16",'project'), which = wx.TreeItemIcon_Normal)
        self.SetPyData(child, project)
        project.item=child
        self.AppendItem(child, "...")
        self.sources=project.getDataObject().getData("General","sources",[]).value
        project.getDataObject().getData("General","costum build",False)
        project.save()
    
    
    def addSource(self,folder,selectedItem=None):
        folder.setSuffix("source")
        if not selectedItem:
            selectedItem=folder.item
        self.SetItemImage(selectedItem, folder.icon(), which = wx.TreeItemIcon_Normal)
        self.sources.append(folder.path)
        self.project.save()
    
    def removeSource(self,folder,selectedItem=None):
        self.sources.remove(folder.path)
        folder.setSuffix("")
        self.SetItemImage(selectedItem, folder.icon(), which = wx.TreeItemIcon_Normal)
        self.project.save()
    
    
    def exploreFile(self,path):
        if sys.platform == "win32":
            subprocess.Popen(r''+FILE_WINDOW+' /select,'+path.replace("/","\\"))
        else:
            subprocess.Popen(FILE_WINDOW+' "'+path+'"')
        
    def addMainSourcePath(self,name,path):
        child = self.AppendItem(self.root, name)
        self.SetItemImage(child, ThemesManager().getDefaultTheme().getWxIdImage("icone_16",'project'), which = wx.TreeItemIcon_Normal)
        self.rootDir=Directory(path)
        self.SetPyData(child, self.rootDir)
        self.AppendItem(child, "...")
        #self.createTree(self.rootDir,child)
    
    def setMainDocument(self,item):
        if isinstance(item,File):
            item.setStatus(File.DOCUMENT_ROOT)
            item.getProject().setDocumentRoot(item.path)
            item=item.item
        else:
            self.GetPyData(item).setStatus(File.DOCUMENT_ROOT)
        
        
        if self.mainItem and isinstance(self.GetPyData(self.mainItem),File):
                self.GetPyData(self.mainItem).setStatus(File.NORMAL_ROOT)
                font2= wx.Font( 9, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL )
                self.SetItemFont( self.mainItem, font2 )
        self.mainItem=item
        font2= wx.Font( 9, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_ITALIC, wx.FONTWEIGHT_BOLD ) 
        self.SetItemFont( item, font2 )
        self.project.save()   
    
            
     
     
    def onStartDrag(self,e):
        self._selected = e.GetItem()
        e.Allow()
        self._freeze=True
    
    def onEndDrag(self,e):
        selectedItemTo=e.GetItem()
        to_=self.GetPyData(selectedItemTo)
        
        #selectedItem=e.GetClientData()
        from_=self.GetPyData(self._selected)
        self.move(from_,to_,selectedItemTo,self._selected)
        #self.move(from_,to_,selectedItemTo,selectedItem)
        #data=self.GetPyData(selectedItem)
        self._freeze=False
        e.Skip()
    
    def moveTo(self,from_=None,to_=None,tItem=None,fItem=None):
        pass
    
    def move(self,from_,to_,tItem,fItem):
        #return
        if from_.moveTo(to_):            
            #self.Collapse(tItem)
            self.Delete(from_.item)
            from_.item=self.AppendItem(tItem,from_.name)
            self.SetItemImage(from_.item, from_.icon(), which = wx.TreeItemIcon_Normal)
            self.SetPyData(from_.item, from_)
            from_.path = to_.path+"/"+from_.name
    
    def rename(self,data,selectedItem):
        self.EditLabel(selectedItem)
    
    def onRenameComplete(self,e):
        selectedItem = e.GetItem()
        data = self.GetPyData(selectedItem)
        if not e.IsEditCancelled():
            name = e.GetLabel()
            if not data.setName(name):
                self.SetItemText(selectedItem,data.name)
        if not os.path.exists(data.path):
            LangsManager().createTemple(data.path, data.data)
                    
    def onContextMenu(self,e):
        selectedItem=e.GetItem()
        data=self.GetPyData(selectedItem)
        menu=Menu(Core().getMainFrame())
        
        if isinstance(data,File):
            menu.quickMenu("Open")
            menu.quickMenu("Execute")
            if FILE_WINDOW:
                menu.quickMenu("Show in "+FILE_WINDOW).setCommand("explore",data.path)
                menu.quickMenu("Show in "+FILE_WINDOW).setImage(ThemesManager().getDefaultTheme().getImage("explore","icone_16"))
            menu.quickMenu("|file")
            if data.getStatus()==File.DOCUMENT_ROOT:
                menu.quickMenu("[x]Main Target").setCommand("project/setMainDocument",data)
            else:
                menu.quickMenu("[]Main Target").setCommand("project/setMainDocument",data)
            #menu.quickMenu("Sub Document")
        else:
            menu.quickMenu("Add")
            temps=LangsManager().getTemplatesList()
            cpt=0
            for temp in temps:
                cpt+=1
                if cpt>10: break
                name=os.path.basename(temp)
                ext=os.path.splitext(name)[1][1:]
                try:
                    img=ThemesManager().getDefaultTheme().getImage('file_'+ext,"file_16")
                except:
                    img=ThemesManager().getDefaultTheme().getImage('file',"file_16")
                    
                m=menu.quickMenu("Add",name)
                m.setImage(img)
                m.setCommand("create_template",data,temp)
            menu.quickMenu("Add","|more","Other")
            menu.quickMenu("|add")
            if FILE_WINDOW:
                menu.quickMenu("Show in "+FILE_WINDOW).setCommand("explore",data.path)
                menu.quickMenu("Show in "+FILE_WINDOW).setImage(ThemesManager().getDefaultTheme().getImage("explore","icone_16"))
            menu.quickMenu("Find in folder").setImage(ThemesManager().getDefaultTheme().getImage("folder-search","icone_16"))
            
            if not isinstance(data,Project):
                menu.quickMenu("|folder")
                try:
                    self.sources.index(data.path)
                    menu.quickMenu("Remove Source Path").setCommand("project/removeSource",data,selectedItem)
                    menu.quickMenu("Remove Source Path").setImage(ThemesManager().getDefaultTheme().getImage("remove_source","icone_16"))
                except:
                    menu.quickMenu("Add Source Path").setCommand("project/addSource",data,selectedItem)
                    menu.quickMenu("Add Source Path").setImage(ThemesManager().getDefaultTheme().getImage("add_source","icone_16"))
            
        menu.quickMenu("|action")
        menu.quickMenu("Copy")
        menu.quickMenu("Cut")
        menu.quickMenu("Past")
        menu.quickMenu("Rename").setCommand("project/rename",data,selectedItem)
        menu.quickMenu("Delete")
        menu.quickMenu("|infos")
        if isinstance(data,Project):
            menu.quickMenu("Properties").setCommand("project/properties",data)
        else:
            menu.quickMenu("Infos")
        ## addEventListener(MouseEvent.MOUSE_CLICK,self.onRename)
        menu.build()
        self.Parent.PopupMenu(menu)        
        return menu
        
    def createTree(self,dir_,parent):
        dir_.read()
        l=dir_.getContent()
        dir_.item=parent
        self.DeleteChildren(parent)
        for ind in l:
            child = self.AppendItem(parent, ind.name)
            try:
                self.sources.index(ind.path)
                ind.setSuffix("source")
            except:
                pass
            ind.item = child
            ind.parent = dir_
            self.SetPyData(child, ind)
            font2= wx.Font( 9, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL )
            self.SetItemFont( child, font2 )
            self.SetItemImage(child, ind.icon(), which = wx.TreeItemIcon_Normal)
            
            if isinstance(ind, Directory):
                ind.read()
                self.AppendItem(child, "...")
            elif ind.getProject().name+"/"+ind.getProject().getDocumentRoot()==ind.getPath():
                self.setMainDocument(child)

        
    def onLeftDClick(self,e):
        pt = e.GetPosition();
        item, flags = self.HitTest(pt)
        data=self.GetPyData(item)
        if isinstance(data,File):
            CommandManager().execute("open",data.path)
        e.Skip()
    
    def onExpand(self,e):
        try:
            selectedItem = e.GetItem();
            data=self.GetPyData(selectedItem)
            data.item=selectedItem

            if isinstance(data,Directory):
                data.read()
                data.setState(Directory.OPEN)
                if not isinstance(data,Project):
                    self.SetItemImage(selectedItem, data.icon(), which = wx.TreeItemIcon_Normal)
                self.createTree(data,selectedItem)
        except:
            pass

    def onCollapsing(self,e):
        try:
            selectedItem = e.GetItem();
            data=self.GetPyData(selectedItem)
            data.item=selectedItem
            data.setState(Directory.CLOSE)
            if not isinstance(data,Project): 
                self.SetItemImage(selectedItem, data.icon(), which = wx.TreeItemIcon_Normal)
        except:
            pass
    

        